import {Component, Input, OnInit} from '@angular/core';
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import Draw from 'ol/interaction/Draw.js';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer.js';
import {OSM, Vector as VectorSource} from 'ol/source.js';
import {UtilComponent} from '../../interface/util-component.interface';

@Component({
    selector: 'kylin-freehand-draw',
    templateUrl: './freehand-draw.component.html',
    styleUrls: ['./freehand-draw.component.less']
})
export class FreehandDrawComponent implements OnInit, UtilComponent {
   // ---------- 接口实现 begin -------------- //
    hasContent = true;
    map: Map;

    @Input() set data(val) {
        Object.assign(this, val);
    };

    // ---------- 接口实现 end ---------------- //

    selectedValue = 'LineString';
    typeList: any[];

    raster;
    source;
    vector;
    draw;
    constructor() {
    }

    ngOnInit() {
        this.getTypeList();
        this.initMap();
        this.addInteraction(this.selectedValue)
    }

    getTypeList() {
        this.typeList = [
            {
                value: 'LineString',
                label: '线',
            },
            {
                value: 'Polygon',
                label: '面',
            },
            {
                value: 'Circle',
                label: '圆圈',
            },
            {
                value: 'None',
                label: '无',
            },

        ]
    }

    initMap() {
        this.raster = new TileLayer({
            source: new OSM()
        });
        this.source = new VectorSource({wrapX: false});
        this.vector = new VectorLayer({
            source: this.source
        });
        this.map.addLayer(this.raster);
        this.map.addLayer(this.vector);
    }

    log(value): void {
        this.map.removeInteraction(this.draw);
        this.addInteraction(value);
    }

    addInteraction(value) {
        if (value !== 'None') {
            this.draw = new Draw({
                source: this.source,
                type: value,
                freehand: true
            });
            this.map.addInteraction(this.draw);
        } else {
            this.map.removeInteraction(this.draw)
        }
    }

    cancel(options?: any): any {
        this.map.removeLayer(this.raster);
        this.map.removeLayer(this.vector);
        this.map.removeInteraction(this.draw)
    }

}
